package day15.work;

import com.rabbitmq.client.*;
import util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Rec1
 * @Description Rec1
 * @Author 孙峰
 * @Date 2020/4/1 9:23
 * @Version 1.0
 */
public class Rec1 {
    private final static String QUEUE_NAME = "test_work_queue";
    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false, false, null);
        //channel.basicQos(1)指该消费者在接收到队列里的消息但没有返回确认结果之前,队列不会将新的消息分发给该消费者。
        // 队列中没有被消费的消息不会被删除，还是存在于队列中
        channel.basicQos(1);
        //定义队列消费者
        DefaultConsumer consumer=    new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("[消费者1]接受消息"+msg+"!");
                try {
                    //模拟消费耗时
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //监听队列
        channel.basicConsume(QUEUE_NAME,false,consumer);

    }
}
